<template>
  <!-- 400px -->
  <div class="asc-model-page">
    <div class="page_content" style="height: 100%;width: 0;flex: 4;">
      <a-card
      :bordered="false" 
      class="page-card"
      style="width:auto; height: 100%;"
      :bodyStyle="{padding:'0px'}"
      >
        <div slot="title" class="page-card-title">
          <span>模型管理</span>
          <template v-if="rowSelectionOpen">
            <a-icon style="position: absolute;right: 60px;" 
              :class="`anticon-${this.selecteRowKeys.length? 'ok anticon-action':'no'} `"
              title="提交" 
              @click="submitAction" 
              type="check"
            />
            <a-icon style="position: absolute;right: 20px;" class="anticon-ok anticon-action"
              title="取消" 
              @click="rowSelectionOpen = false;selecteRowKeys=[]" 
              type="close"
            />
          </template>
          <template v-else>
            <a-upload
            style="position: absolute;right: 100px;"
            :showUploadList="false"
            accept=".json"
            :customRequest="()=>{}"
            :before-upload="uploadmodel">
              <a-icon
                class="anticon-ok anticon-action"
                title="导入模型"
                type="upload"
              />
            </a-upload>
            <a-icon style="position: absolute;right: 60px;" class="anticon-ok anticon-action"
              title="模型比较"
              @click="rowSelectionOpen=true;tag=1"
              type="retweet"
              :rotate="90"
            />
            <a-icon style="position: absolute;right: 20px;" class="anticon-ok anticon-action"
              title="删除模型"
              @click="rowSelectionOpen=true;tag=0"
              type="delete" 
            />
          </template>
        </div>
        <a-table
          :data-source="modelList"
          :loading="!isCreated"
          :rowKey="(record,index)=>JSON.stringify({id:record.id,name:record.name,index})"
          :pagination="false"
          :bordered="true"
          :locale="{filterConfirm: '确认',filterReset: '重置'}"
          :columns="columns"
          :scroll="{y:'calc(100vh - 131px)'}"
          :customRow="rowClick"
          :rowClassName="(record) => {
            const {title,description} = record.edit
            return title||description? 'selected' : 'normal' }"
          :rowSelection="rowSelectionOpen? {
            selectedRowKeys:selecteRowKeys,
            onChange:(selectedRowKeys) => {selecteRowKeys = selectedRowKeys},
          }:null"
        >
          <template slot="name" slot-scope="value,item" >
            <a-input v-if="item.edit.name" 
            :defaultValue="value"
            @pressEnter="(e)=>{ changeMessage(e,item,'name') }"
            />
            <a-dropdown :trigger="['contextmenu']" v-else>
              <span
              @dblclick.stop = "item.edit.name = !item.edit.name">
                {{value}}
              </span>
              <a-menu slot="overlay">
                <a-menu-item @click="showModel(item)">
                  <span><a-icon type="link" />恢复工程文件</span>
                </a-menu-item>
                <a-menu-item v-if="item.type==0" @click="showModel(item)">
                  <span><a-icon type="download" />模型导出</span>
                </a-menu-item>
              </a-menu>
            </a-dropdown>
          </template>
          <template slot="desc" slot-scope="value,item">
            <a-input v-if="item.edit.description" 
            :defaultValue="value"
            @pressEnter="(e)=>{ changeMessage(e,item,'description') }"
            />
            <span
             @dblclick.stop = "item.edit.description = !item.edit.description"
             v-else>{{value}}</span>
          </template>
          <span 
            slot="type" 
            slot-scope="value"
            :style="`color:${['orange','green','blue','purple'][value]};cursor: pointer;`"
          >
            {{ menuList[value] }}
          </span>
        </a-table>
      </a-card>
    </div>
    
    <transition name="modelMode">
      <div class="ant-modal-mask" v-show="reportVisible" @click="reportVisible = false;heightList=[]"></div>
    </transition>
    <transition name="modelMode">
      <div class="modelMode" v-show="reportVisible">
        <div class="title">
          <div style="display: flex;">
            <span class="mastTitle">{{resultInfo.name}}</span>
          </div>
          <div style="display: flex;">
            <!-- //*不显示这个 -->
            <a-icon title="删除报告" type="delete" @click="resultRemove"/>
            <a-icon title="下载报告" type="download" @click="resultDownload"/>
            <!-- //*模型比较显示这个 -->
            <!-- <a-icon v-if="" title="保存报告" type="save" @click="resultSave"/> -->
            <a-icon title="关闭" @click="reportVisible = false;heightList=[]" type="close" />
          </div>
        </div>
        <div class="content">
          <div class="pdfPage" v-for="i in resultInfo.pageNum">
            <a-divider orientation="left" :id="`page:${i}`">
              <span>{{`page：${i}`}}</span>
            </a-divider>
            <v-pdf 
            ref="pdf" 
            :src="resultInfo.url" 
            :key="`${resultInfo.url}-page:${i}`" 
            :page="i+1"
            >
            </v-pdf>
          </div>
        </div>
      </div>
    </transition>
    <a-modal
    :visible="visible"
    @cancel="visible=false"
    :title="tag==1?'模型比较':tag==0?'删除模型':'ERROR'"
    okText="确认"
    :okType="tag==0?'danger':'primary'"
    cancelText="取消"
    :confirmLoading="compareLoading"
    @ok="tag==1?compareModel():tag==0? _delModel():()=>{}"
    >
      <div class="modal-body-div">
        {{tag==1?'模型比较':tag==0?'删除模型':'ERROR'}}
      </div>
      <div v-if="tag==1" class="modal-body-div">
        <span class="ant-form-item-required">选择样本集:</span>
        <a-select
          show-search
          placeholder="选择样本集"
          option-filter-prop="children"
          style="width: 100%"
          :filter-option="true"
          :value="sampleId"
        >
          <a-select-option
           @click="sampleId = item.id"
           v-for="item in sampleList"
           :value="item.id">
            {{item.title}}
          </a-select-option>
        </a-select>
      </div>
    </a-modal>
  </div>
</template>

<script>
  // 请求
  import vPdf from 'vue-pdf'
  import Vue from 'vue'
  import { exportFile,base64ToBlob,sleep,dateFormat } from '@/utils/functions'
  import { 
    getModelList,
    getSampleList,
    delModel,
    getModel,
    changeModel,
    runModelCompare
  } from '@/axios/api'
  import { getStore } from '@/utils/StoreOpers'
  import { menuList } from '@/conf.js'
  export default {
    name: 'ModelManager',
    components: {
      vPdf
    },
    data() {
      return {
        tag:0,//排序方式
        sampleList:[],
        sampleId:"请选择样本集",
        compareNum:2,//两个模型进行比较
        leftShow:0,//flex
        compare:null,//compareNum个false
        compareInfo:null,
        reportVisible: false, //结果展示
        compareLoading: false,
        modelList: [], //全部模型信息
        resultInfo: { //结果信息
          title: '模型',
          url: undefined,
          pageNum: undefined,
        },
        visible:false,
        columnNum:5,
        isCreated:false,
        menuList:Object.freeze([...menuList,'用户上传']),
        timer:null,
        thisItem:{},
        columns:[{
          title:'模型备注',
          dataIndex:'name',
          ellipsis:true,
          align:'left',
          width:150,
          sorter: (a, b) => a.name.localeCompare(b.name),
          scopedSlots: {customRender: 'name'}
        },{
          title: '类型',
          dataIndex:'type',
          ellipsis:true,
          scopedSlots: {customRender: 'type'},
          filters:[...menuList,'用户上传'].map((text,value)=>{
            return {text,value}
          }),
          onFilter: (value, record) => record.type === value,
          width:150,
        },{
          title: '创建时间',
          dataIndex:'createTime',
          ellipsis:true,
          sorter: (a, b) => new Date(a.createTime) - new Date(b.createTime),
          width:150,
        },{
          title: '最近保存',
          dataIndex:'saveTime',
          ellipsis:true,
          sorter: (a, b) => new Date(a.saveTime) - new Date(b.saveTime),
          width:150,
        },{
          title: '描述',
          dataIndex:'description',
          ellipsis:true,
          scopedSlots: {customRender: 'desc'}
        }],
        rowClick:record => ({
          on: {
            dblclick:()=>{
              const {name,description} = record.edit
              if(name || description)
                record.edit = {name:false,description:false}
              if(!name && !description)
                record.edit = {name:true,description:true}
            },
            contextmenu:e=>{
              const {pageX,pageY} = e
              e.preventDefault()
              console.log(pageX,pageY,record.id)
            }
          }
        }),
        rowSelectionOpen:false,
        selecteRowKeys:[],
        tag:0,//标记任务
        
      }
    },
    watch: {
    },
    destroyed() {
      this.$message.destroy()
    },
    async created() {
      console.log({menuList})
      this.compare = new Array(this.compareNum).fill(false)
      // const modelList = await 
      /* console.log(e)
      const {sampleList} = e.data
      sampleList.map(e=>{
        e.edit={title:false,description:false}
        if(e.fileInfo){
          const {total} = e.fileInfo
          const X_Y = total.match(/\d+/g)
          e.fileInfo.total = {value:total,x:X_Y[0],y:X_Y[1]}
        }
      })
      this.sampleList = sampleList */
      await getModelList().then(e=>{
        const { modelList } = e.data
        modelList.map(e=>{
          e.edit={name:false,description:false}
        })
        this.modelList = modelList
      })
      this.isCreated = true
      console.log(this.modelList)
    },
    destroyed() {
      this.$message.destroy()
    },
    methods: {
      async uploadmodel(file){
        const { name,size } = file
        await this.$confirm({
          title: '上传模型',
          okText: '上传',
          cancelText: '取消',
          content:(
            <div>上传自定义模型文件:{name}</div>
          ),
          onOk:async ()=>{
            let id = await sleep(2000)
            id = Math.round(Math.random()*10000)
            console.log('上传',{file,modelList:this.modelList,id})
            this.$message.success('上传成功')
            const time = dateFormat("YYYY-MM-DD hh:mm:ss", new Date())
            this.modelList.unshift({
              id,name,
              description:`用户上传-${name}`,
              type:4,
              createTime:time,
              saveTime:time,
              edit:{
                description:true,
                name:true,
              }
            })
          }
        })
      },
      async submitAction(){
        if(this.selecteRowKeys.length === 0) return 
        console.log(`tag=${this.tag}`)
        if (this.tag == 1 && !this.sampleList.length)
          await getSampleList().then(e=>{this.sampleList = e.data.sampleList})
        this.visible = true
      },
      changeMessage(e,item,attr){
        const {_value} = e.srcElement || e.target
        const source = item[attr]
        if (_value === source) { item.edit[attr] = false;return }
        const { id } = item
        this.$message.loading({content:"修改中...",duration:0,key:`LOADING${id}`})
        const postData = {id}
        postData[attr] = _value
        console.log(postData)
        changeModel(postData).then(e=>{
          this.$message.success({content:"修改成功",key:`LOADING${id}`})
          item[attr] = _value
          item.edit[attr] = false
        }).catch(()=>{
          this.$message.error({content:"修改失败",key:`LOADING${id}`})
        })
      },
      async saveModel(){
        const { id,name,description,index1,index2 } = this.thisItem
        const item = this.modelList[index1][index2]
        const postData = {id}
        if(name !== item.name) postData.name = name
        if(description !== item.description) postData.description = description
        if(postData.name || postData.description){
          console.log(postData)
          await changeModel(postData).then(e=>{
            item.description = description
            item.name = name
          })
        }
        this.visible = false
      },
      showModel(item){
        const { id:modeid,type } = item
        const name = menuList[type]
        this.$router.push({name,query:{modeid}})
      },
      _delModel(){
        let sign = true
        const actionFun = async () => {
          for (let i=this.selecteRowKeys.length-1; i>=0; i--){
            const params = JSON.parse(this.selecteRowKeys[i])
            const {id,name,index} = params
            await delModel({id})
                  .then(e=>{
                    this.modelList.splice(index, 1)
                    this.$message.success({content:`${name} - 删除成功`,key:"DEL_MESSAGE"})
                    this.selecteRowKeys.splice(i,1)
                  })
                  .catch(e=>{
                    sign = false
                  })
          }
        }
        this.visible = false
        const msg = this.$message.loading({content:`样本集${this.tag? '下载':'删除'}中`,duration:0})
        actionFun().then(e=>{
          msg()
          this.$message.success(`样本集${this.tag? '下载':'删除'}完成`)
          if(sign) this.rowSelectionOpen = false
        })
      },     
      async compareModel(){
        const { sampleId,selecteRowKeys } = this
        if(!selecteRowKeys.length || isNaN(Number(sampleId))){
          this.$message.error("请选择样本集")
          return
        }
        const modelIds = selecteRowKeys.map(e=>JSON.parse(e).id).join(",")
        const postdata = {sampleId,modelIds}
        this.compareLoading = true
        // const loadingmsg = this.$message.loading(`模型比较...`)
        const url = await runModelCompare(postdata).then(e=>{
          if(Object.prototype.toString.call(e)=='[object Blob]'){
            const blob = new Blob([e],{type: 'application/pdf'})
            const url = window.URL.createObjectURL(blob)
            return url
          }
        }).catch(e=>null)
        const title = "模型比较"
        await this.modelShow(url,title)
        this.compareLoading = false
        this.visible = false
        // loadingmsg()
      },
      modelShow(url,title) {
        if (!url){
          this.$message.error('加载失败')
          return
        }
        vPdf.createLoadingTask(url).promise.then(pdf => {
          console.log(`total:${pdf.numPages}`)
          this.resultInfo = {
            title,
            url,
            pageNum: pdf.numPages - 1
          }
          this.$nextTick(() => {
            this.reportVisible = true
            this.$nextTick(() => {
              document.getElementsByClassName('content')[0].scrollTop = 0
            })
          })
        }).catch((err) => {
          this.$message.error('pdf加载失败')
        })
      },
      resultRemove(){
        this.$message.info("删除该模型结果")
      },
      resultDownload(){
        const { resultInfo:{url} } = this
        this.$message.info("下载模型结果")
        const fileName = `比较报告.pdf`
        exportFile(url,fileName)
      },
    },
    computed: {},
  }
</script>

<style lang="less" scoped>
  @titleHeight: 40px;
  @contentPadding: 5px;
  @contentHeight: 10%; //contentHeight = (100% - 2*@contentHeight)
  @contentWidth: 10%; //contentWidth = (100% - 2*@contentWidth)
  @pdfPageDogEar: 80px; //pdf右上角折角
  //模型比较的提示
  /deep/.ant-card-head{
    height: @titleHeight;
    min-height: @titleHeight;
    display: flex;
    font-weight: 700;
  }
  /deep/.ant-card-body{
    overflow: scroll;
    height:calc(100% - @titleHeight);
  }
  .ant-modal-mask {
    //阴影
    z-index: 998 !important;
    // background-color: #000;
  }

  .modelMode {
    //模型展示
    position: absolute;
    top: @contentHeight;
    bottom: @contentHeight;
    left: @contentWidth;
    right: @contentWidth;
    // left: 50%;
    // transform: translate(-50%,0);
    z-index: 999;
    background: #fff;
    border-radius: 5px;
    display: flex;
    flex-flow: column nowrap;

    &-code {
      //展示代码
      bottom: 10%;
    }
    .title {
      height: @titleHeight;
      display: flex;
      width: calc(100% - @contentPadding - @contentPadding);
      justify-content: space-between;
      align-items: flex-end;
      font-size: 24px;
      margin: 0 @contentPadding;
      user-select: none;
      -moz-user-select: none;
      -webkit-user-select: none;
      -ms-user-select: none;
      border-bottom: 1px solid rgba(0, 0, 0, 0.1);

      .mastTitle {
        //主标题
        margin-right: 10px;
      }

      .modeltitle {
        //小菜单
        transition: all .3;
        margin: 0 5px;

        &-select {}

        &-noselect {
          zoom: 0.7;
          -moz-transform: scale(0.5);
          opacity: 0.5;
          // align-self: flex-end;
          cursor: pointer;

          &:hover {
            opacity: 1;
          }
        }
      }

      .anticon {
        //关闭按钮
        padding: 3px;
        cursor: pointer;
        border-radius: 3px;
        align-self: center;
        margin-left: 20px;
        &:hover {
          background: rgba(0, 0, 0, 0.03);
          color: #000;
        }
        align-self: center;
      }
    }

    .content {
      /*    display: flex;
    justify-content: space-between; */
      height: calc(100% - @titleHeight);
      transition: all .3s ease;
      margin: 0 @contentPadding @contentPadding @contentPadding;
      overflow: scroll;
      .pdfPage {
        //pfd展示
        // >span {
        //   -webkit-clip-path: polygon(calc(100% - @pdfPageDogEar) 0px, 100% @pdfPageDogEar, 100% 100%, 0 100%, 0 0);
        //   clip-path: polygon(calc(100% - @pdfPageDogEar) 0px, 100% @pdfPageDogEar, 100% 100%, 0 100%, 0 0);
        // }
        .ant-divider {
          //分割线 - 不要剪切掉
          // &::before,
          &::after {
            border: none !important;
          }
        }
      }

      &::-webkit-scrollbar {
        height: 0px !important;
        width: 9px !important;
      }

      &::-webkit-scrollbar-thumb {
        border-radius: 0;
        border-style: dashed;
        background-color: rgba(157, 165, 183, 0.4);
        border-color: transparent;
        border-width: 2px;
        background-clip: padding-box;
      }

      &::-webkit-scrollbar-thumb:hover {
        background: rgba(157, 165, 183, 0.7)
      }
    }

    &-enter-active,
    &-leave-active {
      position: absolute;
      transition: all .5s ease;
    }

    &-enter,
    &-leave-to {
      position: absolute;
      transform: scale(0.5);
      transform: translate(-150%, -150%);
      opacity: 1;
    }
  }
</style>
<style lang="less" scoped>
@titleHeight:40px;
@pageMargin: 5px;
.samples-move {
  transition: transform 1s;
}
.asc-model-page {
  display: flex;
  margin: @pageMargin;
  height: calc(100vh - 45px - @pageMargin - @pageMargin);
  overflow: hidden;//*不知道从哪儿溢出来的
  .asc-title {
    width: 0;
    transition: all 1s;
    transform: translate(-2.5px, 0);//5/2
    //padding-bottom:10px;
    &-title{
      font-size: 20px;
      text-align: center;
      height: @titleHeight;
      border-bottom: 2px solid #acacac;
      >span{
        white-space: nowrap;
        font-weight: 700;
      }
    }
    &-main{
      height:calc(100% -  @titleHeight);
      text-align: center;
      // padding: 24px;
      .compare{
        // margin: 6px 0px;
        // width: 50%;
        margin: 10px;
        display: flex;
        flex-direction: column;
        align-items: center;
        &-title{
          width: 100%;
          text-align: left;
          white-space: nowrap;
        }
        &-photo{
          height: 40px;
          width: 40px;
          border: 2px dotted #acacac;
          border-radius: 3px;
          box-sizing: content-box;
        }
        &-photo-have:hover+.compare-del{
          // display: block;
          opacity: 1;
          transform: translate(0,-50%);
        }
        &-del{
          transition: all 1s;
          // display: none;
          position: absolute;
          opacity: 0;
          transform: translate(0px, 100%);
          width: 44px;
          padding: 0;
          &:hover{
            // display: block;
            opacity: 1;
            transform: translate(0,-50%);
          }
        }
      }
    }
  }
  // .hand-scroll {
  //   &::-webkit-scrollbar {
  //     height: 0px !important;
  //     width: 0px !important;
  //   }
  //   display: flex;
  //   min-height: 100%;
  //   background: #fff;
  // }
  .model-box{
    // margin: 5px;
    min-width: 80px;
    width: 80px;
    transition: all 1s; 
    display: flex;
    >div:nth-child(1){
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
    }
    .model-name{
      width:100%;
      overflow-wrap:anywhere;
      color: rgba(0,0,0,0.5);
      cursor: pointer;
      transition: all 0.4s cubic-bezier(0.645, 0.045, 0.355, 1);
      &:hover{
        color: #1890ff;
      }
    }
    &-details{
      overflow: scroll;
      >p{
        display: flex;
        justify-content: space-between;
        align-items: center;
      }
      // &::-webkit-scrollbar {
      //   height: 0px !important;
      //   width: 9px !important;
      // }
    }
  }
}
.page-card{
  
  &-title{
    display: flex;
    align-items: center;
    &-icon{
      margin-left: 50px;
      .change-by{
      margin-left: 5px;
      cursor: pointer;
      transition: all 0.4s cubic-bezier(0.645, 0.045, 0.355, 1);
        &:hover{
          color: #1890ff !important;
        }
      }
    }
  }
  overflow: hidden;
  ::v-deep >.ant-card-body {
    display: flex;
    flex-direction: column;
    overflow-x: hidden;
  }
  .mode-box{
    position: relative;
    width: auto;
    height: calc(25%);
    .ant-divider{
      margin: 5px 0 0 0;
    }
    &-title{
      font-size: 16px;
      font-weight: 700;
    }
    &-main{
      height: calc(100% - 29px);
      display: flex;
      overflow-x: scroll;
      &::-webkit-scrollbar {
        height: 8px !important;
        width: 0px !important;
      }
    }
  }
  .ant-avatar{//头像
    cursor: move;
    cursor: -webkit-grab;
    &:active{
      cursor: -webkit-grabbing;
    }
    &:hover{
      border: 1px solid #f2f4f6;
    }
  }
  .model{
    &-description{//描述
      transition: all .5s;
      cursor: pointer;
      &:hover{
        max-height: 999px !important;
      }
    }
    &-result{//结果
      transition: all .5s;
      cursor: pointer;
      &:hover{
        max-height: 999px !important;
      }
      &-item{
        
      }
    }
  }
}
  /deep/.ant-card-body {
    width: 100%;

    .showReport {
      cursor: pointer;
      margin-left: 5px;
      color: rgba(0, 0, 0, 0.9);
      transition: all 0.4s cubic-bezier(0.645, 0.045, 0.355, 1);

      &:hover {
        color: #1890ff;
      }
    }
  }


  .table-operator {
    display: flex;
    justify-content: flex-start;
    margin-bottom: 20px;
  }

  .search-wrap {
    margin-bottom: 20px;
    overflow: hidden;
    .screen-box {
      margin-right: 20px;
      margin-bottom: 10px;
      float: left;
      height: 34px;
    }
  }

  .search-input-box {
    float: left;
    width: calc(100% - 200px);
  }

  .search-input {
    margin-right: 20px;
  }

  // @media screen and (max-width: 1370px) {
  //   .screen-input {
  //     width: 140px;
  //   }
  // }
</style>
